<?php
/**
 * 【购物车】修改接口 
 * @author webopenfather
 */

// 导入公共库文件
include '../../util/function.php';
include '../../util/db.php';
include '../../util/token.php'; // 这个文件中声明了$userId

// 1. 接受数据
$goodsId = @$_REQUEST['goodsId'];
$buyNum = @$_REQUEST['buyNum'];
if (!$goodsId || !$buyNum) response(400, '参数有误');

// 2. 操作数据库（注：$pdo变量在db.php文件中定义了 所以可以直接用）
// 切记得校验库存是否充足
$pdoStatement = $pdo->query("select * from ecs_goods where goods_id = {$goodsId}");
$goodsInfo = $pdoStatement->fetch(PDO::FETCH_ASSOC);
if (!$goodsInfo) response(400, '参数有误-商品不存在');
if ($goodsInfo['goods_number'] < $buyNum ) response(400, "【{$goodsInfo['goods_name']}】库存不足");
$rs = $pdo->exec("update ecs_cart set goods_number = {$buyNum} where user_id = {$userId} and goods_id = {$goodsId}");

// 3. 响应数据
if ($rs) {
    response(200, '操作成功');
} else {
    response(500, '操作失败');
}
